#include "GLHeaders.hpp"
#include "Texture.hpp"
#include "Color.hpp"
#include "Interpolation.hpp"
#include "../Global.hpp"
#include "Background.hpp"

Background_::Background_(void){
  InitTexture();
  InitList();
}

Background_::~Background_(void){
	glDeleteLists(list_id,1);
}

void Background_::Draw(void){
	glCallList(list_id);
}

void Background_::InitList(void){
	list_id = glGenLists(1); // create one DisplayList
	glNewList(list_id, GL_COMPILE);
	GLfloat coef = 1.0f;

  glPushAttrib(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_CURRENT_BIT|GL_TEXTURE_BIT);
  glDisable(GL_DEPTH_TEST);
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glOrtho(0.0f, (GLdouble)window.width, 0.0f, (GLdouble)window.height, -1.0f, 1.0f);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

	glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, text_id);
	glBegin(GL_TRIANGLES);
	glNormal3f( 0.0f, 0.0f, 1.0f); // Front Face
	glColor3f(1.0f, 1.0f, 1.0f);
 	glTexCoord2f(0.0f, 0.0f);glVertex3f( 0.0f, 0.0f, 0.0f);
	glTexCoord2f(coef, 0.0f);glVertex3f( (GLfloat)window.width, 0.0f, 0.0f);
	glTexCoord2f(coef, coef);glVertex3f( (GLfloat)window.width, (GLfloat)window.height, 0.0f);

	glTexCoord2f(coef, coef);glVertex3f( (GLfloat)window.width, (GLfloat)window.height, 0.0f);
	glTexCoord2f(0.0f, coef);glVertex3f( 0.0f, (GLfloat)window.height, 0.0f);
	glTexCoord2f(0.0f, 0.0f);glVertex3f( 0.0f, 0.0f, 0.0f);
	glEnd();
  glPopMatrix();
	glPopAttrib();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
	glEndList();
}

void Background_::InitTexture(void){
	Texture tex(window.width, window.height);
  
  tex = tex.Fill(
      Color::Color(0.0f, 0.0f, 0.0f, 1.0f), 
      Color::Color(0.0f, 0.0f, 0.0f, 1.0f), 
      Color::Color(0.0f, 0.0f, 0.25f, 1.0f),
      Color::Color(0.0f, 0.0f, 0.25f, 1.0f),
      LINEAR);

  glGenTextures(1, &text_id);
	glBindTexture(GL_TEXTURE_2D, text_id);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, mizu);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLubyte *)tex.data);
}

